import React, { FC, useEffect } from "react";
import {
  Typography,
  Space,
  Form,
  Input,
  Button,
  Checkbox,
  message,
} from "antd";
import { UserAddOutlined } from "@ant-design/icons";
import { REGISTER_PATHNAME, MANAGE_INDEX_PATHNAME } from "../../router";
import style from "./index.module.scss";
import { Link, useNavigate } from "react-router-dom";
import { useRequest } from "ahooks";
import { loginService } from "../../services/user";
import { setToken } from "../../utils/user-token";

const { Title } = Typography;
const USERNAME_KEY = "USERNAME";
const PASSWORD_KEY = "PASSWORD";
function setUserInfoStorage(username: string, password: string) {
  localStorage.setItem(USERNAME_KEY, username);
  localStorage.setItem(PASSWORD_KEY, password);
}
function deleteInfoStorage() {
  localStorage.removeItem(USERNAME_KEY);
  localStorage.removeItem(PASSWORD_KEY);
}
function getUserInfoStorage() {
  return {
    username: localStorage.getItem(USERNAME_KEY),
    password: localStorage.getItem(PASSWORD_KEY),
  };
}

const Login: FC = () => {
  const [form] = Form.useForm();

  const navigate = useNavigate();

  const { run } = useRequest(
    async (values) => {
      const { username, password } = values;
      const data = await loginService(username, password);
      return data;
    },
    {
      manual: true,
      onSuccess(result) {
        message.success("登录成功");
        navigate(MANAGE_INDEX_PATHNAME);
        const { token = "" } = result;
        setToken(token);
      },
      onError() {
        message.error("登录失败");
      },
    }
  );

  const onFinish = (value: any) => {
    console.log(value);
    const { remenber, username, password } = value;

    run(value);
    if (remenber) {
      setUserInfoStorage(username, password);
    } else {
      deleteInfoStorage();
    }
  };

  useEffect(() => {
    const { username, password } = getUserInfoStorage();
    form.setFieldsValue({ password, username });
  }, []);
  return (
    <div className={style.container}>
      <div>
        <Space>
          <Title level={2}>
            <UserAddOutlined />
          </Title>
          <Title level={2}>登陆</Title>
        </Space>
      </div>
      <div>
        <Form
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          initialValues={{ remenber: true }}
          form={form}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              { required: true, message: "请输入用户名" },
              {
                type: "string",
                min: 5,
                max: 16,
                message: "字符长度在5-16之间",
              },
              {
                pattern: /^\w+$/,
                message: "只能是字母拼音下划线",
              },
            ]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password></Input.Password>
          </Form.Item>
          <Form.Item
            name="remenber"
            valuePropName="checked"
            wrapperCol={{ offset: 8, span: 16 }}
          >
            <Checkbox>记住我</Checkbox>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                登陆
              </Button>
              <Link to={REGISTER_PATHNAME}> 去注册 </Link>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};
export default Login;
